package com.tairan.chapter.flowable.service.impl;

import com.tairan.chapter.flowable.service.DeModelService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.ui.modeler.domain.Model;
import org.flowable.ui.modeler.service.ModelServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class DeModelServiceImpl implements DeModelService {

    private Logger logger = LoggerFactory.getLogger(DeModelServiceImpl.class);

    @Autowired
    private ModelServiceImpl modelService;

    @Autowired
    private RepositoryService repositoryService;

    @Override
    @Transactional(readOnly = false)
    public String deploy(String modelId) {
        Model model = modelService.getModel(modelId);
        byte[] bpmnBytes = modelService.getBpmnXML(model);
        String processName = model.getName();
        if (!StringUtils.endsWith(processName, ".bpmn20.xml")) {
            processName += ".bpmn20.xml";
        }
        Deployment deployment = repositoryService.createDeployment()
                .addBytes(processName, bpmnBytes)
                .name(model.getName())
                .key(model.getKey())
                .deploy();

        logger.debug("流程部署--------deploy：" + deployment);

//        repositoryService.createDeploymentQuery()
//                .deploymentId(deployment.getId())

        return "部署成功，deplymentId=" + deployment.getId();
    }
}
